<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>注册 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body class="login-page">
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>用户注册</h2>

        <div class="card">
            <form th:action="@{/api/users/register}" method="post" id="registerForm" class="login-form">
                <div class="form-group">
                    <label for="username">用户名：</label>
                    <input type="text" id="username" name="username" required>
                </div>

                <div class="form-group">
                    <label for="password">密码：</label>
                    <input type="password" id="password" name="password" required>
                </div>

                <div class="form-group">
                    <label for="phoneNumber">电话号码：</label>
                    <input type="text" id="phoneNumber" name="phoneNumber" placeholder="请输入您的电话号码">
                </div>

                <button type="submit" class="btn">注册</button>

                <div class="form-footer">
                    <p>已有账号？<a th:href="@{/login}">立即登录</a></p>
                </div>
            </form>
        </div>

        <div id="msg"></div>
    </section>
</div>
<script>
    document.getElementById('registerForm').onsubmit = async function(e) {
        e.preventDefault();
        const form = e.target;

        try {
            const res = await fetch(form.action, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    username: form.username.value,
                    password: form.password.value,
                    phoneNumber: form.phoneNumber.value
                })
            });

            const data = await res.json();

            if(data.username) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">注册成功，请登录</div>';
                setTimeout(() => window.location.href = '/login', 1000);
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '注册失败'}</div>`;
            }
        } catch (error) {
            document.getElementById('msg').innerHTML = `<div class="error-msg">注册失败: ${error.message}</div>`;
        }
    };
</script>
</body>
</html> 